package handlers

import (
	"data_view/core"
	"data_view/models"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"io/ioutil"
	"path/filepath"
	"strconv"
	"strings"
)

const (
	DefaultTitle   = "{title}"
	DefaultWidth   = "1920px"
	DefaultHeight  = "1080px"
	DefaultHtml    = "<div id='content'></div>"
	DefaultOptions = "{ID_OPTION}"
	DefaultDatas   = "{ID_DATA}"
)

func ReplaceStr(fileName, oldStr, newStr string) {
	filePath := core.Config.Get("export.path").(string)
	if content, err := ioutil.ReadFile(filePath + fileName); err == nil {
		newContent := strings.Replace(string(content), oldStr, newStr, -1)
		_ = ioutil.WriteFile(filePath+fileName, []byte(newContent), 0)
	}
}

func CopyFile(sourcePath, targetPath string) {
	var (
		err        error
		sourceFile []byte
	)
	filePath := core.Config.Get("export.path").(string)
	if sourceFile, err = ioutil.ReadFile(sourcePath); err != nil {
		fmt.Println(err)
		return
	}
	if err = ioutil.WriteFile(filePath+targetPath, sourceFile, 0777); err != nil {
		fmt.Println(err)
		return
	}
}

// 创建图表离线包
func CreateChartPkg(context iris.Context) {
	var (
		err            error
		id             uint64
		screenInstance *models.ScreenInstanceParams
		imageBg        *models.ImageBg
		dataSources    []*models.DataSource
		appHtmlPath    = "views/app.html"
		appJsPath      = "views/js/app.js"
		imgPath        = "views/image/"
		configPath     = "config.toml"
	)
	// 获取ID
	if id, err = context.Params().GetUint64("id"); err != nil {
		// 错误的请求
		context.StatusCode(iris.StatusBadRequest)
		// 请求参数错误，不能正确格式化
		_, _ = context.JSON(ApiResourceError(core.RequestBodyError))
		return
	}
	// 获取Instance，获取标题和图表大小，填写html和css
	if screenInstance, err = models.GetScreenInstanceById(id); err != nil {
		// 程序内部错误
		context.StatusCode(iris.StatusInternalServerError)
		// 查询数据库错误
		_, _ = context.JSON(ApiResourceError(err.Error()))
		return
	}
	// 设置标题
	ReplaceStr(appHtmlPath, DefaultTitle, screenInstance.InstanceTitle)
	// 设置body大小
	ReplaceStr(appHtmlPath, DefaultWidth, strconv.Itoa(int(screenInstance.InstanceWidth))+"px")
	ReplaceStr(appHtmlPath, DefaultHeight, strconv.Itoa(int(screenInstance.InstanceHeight))+"px")
	// 获取ImageBg，拷贝图片到指定位置
	if imageBg, err = models.GetImageBgById(screenInstance.InstanceBackgroundImg); err != nil {
		// 程序内部错误
		context.StatusCode(iris.StatusInternalServerError)
		// 查询数据库错误
		_, _ = context.JSON(ApiResourceError(err.Error()))
		return
	}
	// 获取图片路径
	sourceImgPath := filepath.FromSlash(core.Config.Get("image.path").(string) + imageBg.ImagePath + string(filepath.Separator) + imageBg.ImageName)
	// 拷贝图片到指定位置
	CopyFile(sourceImgPath, imgPath+string(filepath.Separator)+imageBg.ImageName)
	// 遍历ChartItem,生成HTML结构
	html := "<div id='content' style='background-image: url(\"image/" + imageBg.ImageName + "\")'>\n"
	datas := make(map[string]interface{})
	options := make(map[string]interface{})
	for _, chartItem := range screenInstance.ChartItems {
		// 生成HTML结构
		chartItemHtml := fmt.Sprintf("    <div class='chart' id='%s' style='top:%dpx;left:%dpx;height:%dpx;width:%dpx;' chart-type='%s'></div>\n",
			chartItem["i"].(string),
			chartItem["y"].(uint64),
			chartItem["x"].(uint64),
			chartItem["height"].(uint64),
			chartItem["width"].(uint64),
			chartItem["chartType"].(string))
		html += chartItemHtml
		// 生成Js代码
		options[chartItem["i"].(string)] = chartItem["option"]
		datas[chartItem["i"].(string)] = chartItem["chartData"]
	}
	// 写入HTML结构
	ReplaceStr(appHtmlPath, DefaultHtml, html+"</div>")
	// 写入js代码
	optionsJson, _ := json.Marshal(options)
	ReplaceStr(appJsPath, DefaultOptions, string(optionsJson))
	datasJson, _ := json.Marshal(datas)
	ReplaceStr(appJsPath, DefaultDatas, string(datasJson))
	// 写入数据库连接配置
	if dataSources, err = models.GetDataSourceList(); err != nil {
		// 程序内部错误
		context.StatusCode(iris.StatusInternalServerError)
		// 查询数据库错误
		_, _ = context.JSON(ApiResourceError(err.Error()))
		return
	}
	var dataSourceConfigList string
	for _, dataSource := range dataSources {
		dataSourceConfig := "[" + strconv.Itoa(int(dataSource.DataSourceId)) + "]\n"
		dataSourceConfig += "  dataSourceType = \"" + dataSource.DataSourceType + "\"\n"
		dataSourceConfig += "  dataSourceDatabaseName = \"" + dataSource.DataSourceDatabaseName + "\"\n"
		dataSourceConfig += "  dataSourceIp = \"" + dataSource.DataSourceIp + "\"\n"
		dataSourceConfig += "  dataSourcePort = " + strconv.Itoa(int(dataSource.DataSourcePort)) + "\n"
		dataSourceConfig += "  dataSourceUsername = \"" + dataSource.DataSourceUsername + "\"\n"
		dataSourceConfig += "  dataSourcePassword = \"" + dataSource.DataSourcePassword + "\"\n"
		dataSourceConfigList += dataSourceConfig
	}
	_ = ioutil.WriteFile(core.Config.Get("export.path").(string)+configPath, []byte(dataSourceConfigList), 0)
	context.StatusCode(iris.StatusOK)
	_, _ = context.JSON(ApiResourceSuccess("成功"))
	return
}
